package first.libxml.handlers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import first.liter.AbstractLanguage;
import first.liter.BaseLanguage;
import first.liter.Literature;

public class LitAnalyzerDOM 
{
	private static BaseLanguage bas;
	private static Literature literature;
	
	public static List<Literature> listBuilderLit(Element root) throws SAXException, IOException 
	{
		List<Literature> lit	= new ArrayList<Literature>();
		
		// получение списка дочерних элементов <student>
		NodeList literaturesNodes =root.getElementsByTagName("literature");
		
		Literature literature = null;
		
		for (int i = 0; i < literaturesNodes.getLength(); i++) 
		{
			Element literatureElement =(Element) literaturesNodes.item(i);
			// заполнение объекта literature
			bas=AbstractLanguage.getLanguage(literatureElement.getAttribute("languageLit"));
			
			if (literatureElement.getAttribute("typeOfLiterature").toUpperCase().equals("BOOK")) 
				{
					literature=bas.createBooks(getBabyValue(literatureElement, "nameLit"));
				}
			if (literatureElement.getAttribute("typeOfLiterature").toUpperCase().equals("JOURNAL")) 
				{
				literature=bas.createJournals(getBabyValue(literatureElement, "nameLit"));
				}
			
			literature.setDesc(getBabyValue(literatureElement, "desc"));
			literature.setAuthor(getBabyValue(literatureElement, "author"));
			literature.setIdLit(Integer.parseInt(literatureElement.getAttribute("idLit")));
			literature.setEditNumLit(Integer.parseInt(getBabyValue(literatureElement, "editNumLit")));
			literature.setAmountOfPages(Integer.parseInt(getBabyValue(literatureElement, "amountOfPages")));
			literature.setAvailabilityOfLit(Boolean.parseBoolean(getBabyValue(literatureElement, "availabilityOfLit")));
			
			/*
			// заполнение объекта address
			Element addressElement =
			getBaby(literatureElement, "address");
			address.setCountry(
			getBabyValue(addressElement, "country"));
			 */
			lit.add(literature);
		}
		
		return lit;
	}

	// возвращает дочерний элемент по его имени и родительскому элементу
	private static Element getBaby(Element parent, String childName) 
	{
		NodeList nlist =
		parent.getElementsByTagName(childName);
		Element child = (Element) nlist.item(0);
		return child;
	}
	
	// возвращает текст, содержащийся в элементе
	private static String getBabyValue(Element parent, String childName) 
	{
		Element child = getBaby(parent, childName);
		Node node = child.getFirstChild();
		String value = node.getNodeValue();
		return value;
	}

	
}
